import React, { Component } from 'react';
import { Table, Button, message, Modal } from 'antd';
import { connect } from 'dva';
import Cookies from "js-cookie";
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Ellipsis from '@/components/Ellipsis'
import moment from 'moment';
import styles from './index.less'

const SockJS = window.SockJS;
const Stomp = window.Stomp;
let sock, client;

const columns = (context) => [
    {
        key: '1',
        title:(
            <React.Fragment>
                <Button style={{marginRight:10}} onClick={context.handleDeleteMessage} disabled={!context.state.selectedRowKeys.length>0}>删除</Button>
                <Button style={{marginRight:10}} onClick={context.handleUpdateReadStatus} disabled={!context.state.selectedRowKeys.length>0}>标为已读</Button>
                <Button onClick={context.handleUpdateAllReadStatus} disabled={!parseInt(context.props.count, 0) > 0}>全部标为已读</Button>
            </React.Fragment>
        ),
        render:(text,record)=>{
          return (
            <div className="messages">

              <a className={styles.Ahover}
                onClick={() => context.handleUpdateSingleReadStatus(record)}
              >
                <div className={styles.messagesContent}>
                  <p className="title" style={{ fontSize: 14, marginBottom: 7, display: 'inline-block', fontWeight: 'bold', color: parseInt(record.status, 0) === 1 ? '#999' : '#333' }} >
                    {record.subject}
                  </p>
                  <br />
                  <div style={{ color: parseInt(record.status, 0) === 1 ? '#999' : '#333', width:'100%'}}>
                    <Ellipsis lines={1}>
                        {
                          record.content
                        }
                    </Ellipsis>
                  </div>
                  {/* <span style={{ color: parseInt(record.status, 0) ===2?'#999':'#333'}} dangerouslySetInnerHTML={{__html: record.content}}></span> */}

                </div>
              </a>
              <p style={{ color: '#999' }}>{moment(JSON.parse(record.createTime)).format('YYYY-MM-DD')}</p>
            </div>
          )
        }
    }
]

@connect(({ loading, messages:{  count, data } }) => ({
    loading: loading.effects['messages/fetchMessageList'],
    count,
    data,
}))
class Messages extends Component {

    state={
        selectedRowKeys: [],
    }

    refreshData= (params) =>{
      const { dispatch } = this.props
        dispatch({
            type: 'messages/fetchMessageList',
            payload:params || {}
        })
        dispatch({
            type: 'messages/fetchNotReadCount',
        });
    }

    handleTableChange = (pagination, filters, sorter) => {
        const { field, order } = sorter;
        this.refreshData({
          asc: order ? order.replace("end", "") === "asc" : undefined,
          order: field || undefined,
          page: pagination.current,
          pageSize: pagination.pageSize
        })

    }

    onSelectChange = (selectedRowKeys) => {
        this.setState({
            selectedRowKeys,
        });
    }

    setSelectedRowKeys = () => this.setState({selectedRowKeys:[]})

    handleUpdateSingleReadStatus = (record) =>{
        const { history, dispatch } = this.props
        if (parseInt(record.status, 0) === 0){
            dispatch({
                type: 'messages/getUpdateReadStatus',
                payload:{
                  list: [record.id]
                },
            })
            .then(msg => {
                message.success(msg);
                this.setSelectedRowKeys()
                this.refreshData()
            })
            .catch(errMsg => {
                message.error(errMsg);
            });
        }
        //window.open(`/messages/detail?id=${record.id}`)
        history.push(`/messages/detail?id=${record.id}`)
    }

    handleUpdateReadStatus = () =>{
        this.props.dispatch({
            type: 'messages/getUpdateReadStatus',
            payload:{
              list : this.state.selectedRowKeys
            },
        })
        .then(msg => {
            message.success(msg);
            this.setSelectedRowKeys()
            this.refreshData()
        })
        .catch(errMsg => {
            message.error(errMsg);
        });
    }

    handleUpdateAllReadStatus = () =>{
        this.props.dispatch({
            type: 'messages/getUpdateAllReadStatus',
        })
        .then(msg => {
            message.success(msg);
            this.setSelectedRowKeys()
            this.refreshData()
        })
        .catch(errMsg => {
            message.error(errMsg);
        });
    }

    handleDeleteMessage = () =>{
        const { dispatch } = this.props
        const modalRef = Modal.confirm({
          title: '友情提醒',
          content: '该删除后将不可恢复，是否删除？',
          okText: '确定',
          okType: 'danger',
          cancelText: '取消',
          onOk: () => {
            modalRef && modalRef.destroy()
            dispatch({
                    type: 'messages/getDeleteMessage',
                    payload:{
                        list: this.state.selectedRowKeys
                    },
                })
                .then(msg => {
                    message.success('删除成功');
                    this.setSelectedRowKeys()
                    this.refreshData()
                })
                .catch(errMsg => {
                    message.error(errMsg);
                });
          },
          onCancel() {
            modalRef.destroy()
          }
        })
    }

    initSock = () => {
      try {
          sock = new SockJS(`${window.wsURL}?token=${Cookies.get('token')}`);
          client = Stomp.over(sock);
          console.log('start');
          client.connect({},() => {
              try {
                  client.subscribe(`/user/queue/notice/message`, (sockMessage) => {
                      if(sockMessage && this.handleSubmit){
                        this.refreshData()
                      }
                  });
              } catch (err) {
                  console.log(`webSocket subscribe失败:`);
                  console.log(err);
              }

          // },(error)=>{
          //   console.log(error)
          });
      } catch (err) {
          console.log(`webSocket连接错误:`);
          console.log(err);
      }
    }

    destroySock = () => {
        try {
            client.disconnect();
        } catch (err) {
            console.log(`webSock销毁失败:`);
            console.log(err);
        }
        sock = null;
        client = null;
    }

    componentDidMount(){
      this.refreshData()
      this.initSock()
    }

    componentWillUnmount(){
      this.destroySock()
    }

    render() {
        const { selectedRowKeys } = this.state
        const { loading, count, data:  { list, pagination } } = this.props;

        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };

        return (
          <PageHeaderWrapper
            title={`消息 ${ parseInt(count, 0) > 0 ? `（${count}）` : ''} `}
          >
                <Table
                    size="default"
                    columns={columns(this)}
                    rowKey={record => record.id}
                    rowSelection={rowSelection}
                    dataSource={list}
                    pagination={pagination}
                    loading={loading}
                    onChange={this.handleTableChange}
                />
            </PageHeaderWrapper>
        );
    }
}
export default Messages;
